package ru.picman.ui;

import java.util.HashMap;
import java.util.Map;

import ru.picman.EntityType;
import ru.picman.Pig;
import ru.picman.R;
import ru.picman.Unit;
import ru.picman.util.ImageLibrary;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;

import static ru.picman.EntityType.*;

/**
 * Painter specifically for instances of the Unit class (or one of it's children). 
 * A UnitPainter is linked to a Unit, an a bitmap is linked to the instance of the 
 * painter based on the type of the Unit.
 * @author David
 *
 */
public class UnitPainter
             implements Paintable
{
	/**
	 * Constructor for the UnitPainter.
	 * @param unit - Unit this painter belongs to.
	 */
	public UnitPainter(Unit unit) {
		this.unit = unit;
		this.lastDirection = Unit.DIRECTION_RIGHT;
	}
	

	
	public void paint(Canvas canvas, Paint paint) {
		if (!unit.isVisible())
			return;
		int tileSize = unit.getWorld().getTileSize();
		canvas.drawBitmap(getBitmap(),unit.getX() * tileSize,unit.getY() * tileSize,paint);
	}
	
	/**
	 * Retrieves the bitmap corresponding to the current state of the Unit
	 * this UnitPainter belongs to.
	 * @return
	 */
	private Bitmap getBitmap() {
		int direction = unit.getDirection();
		lastDirection = (direction < 0 ? lastDirection : direction);
		int[] drawables = typeToImageIdxs.get(unit.getType());
		int id;
		if (unit.getType() == EntityType.BIRD)
			id = drawables[Math.min(lastDirection,drawables.length-1)];
		else
			id = drawables[((Pig)unit).isFrozen() ? 1 : 0];
		return getBitmap(id);
	}
	
	/**
	 * Returns a specified bitmap.
	 * @param id - Id of the desired bitmap, as stored in the generated R-class.
	 * @return
	 */
	private Bitmap getBitmap(int id) {
		Bitmap bitmap = ImageLibrary.getBitmap(id);
		if (bitmap == null) {
			int tileSize = unit.getWorld().getTileSize();
			bitmap = ImageLibrary.load(id,tileSize,tileSize).second;
		}
		return bitmap;
	}
	
	//
	
	private int                          lastDirection;
	
	private final Unit                   unit;
	
	/**
	 * This is the map with each Entity.Type and the ids of the images that
	 * belong to it. For the moving entities, the convention is to store
	 * clockwise, starting at position up.
	 */
	private static final Map<EntityType,int[]> typeToImageIdxs;
	
	static {
		typeToImageIdxs = new HashMap<EntityType,int[]>();
		typeToImageIdxs.put(BIRD,new int[] {R.drawable.bird_u,	// up
                                            R.drawable.bird_l,	// left
                                            R.drawable.bird_d,	// down
                                            R.drawable.bird_r});// right);
		
		typeToImageIdxs.put(PIG,new int[] {R.drawable.pig_normal,
										   R.drawable.pig_frozen});
	}
	
}
